<?php
set_time_limit(300);
defined('IN_PHPCMS') or exit('No permission resources.');
// 模型缓存路径
define('CACHE_MODEL_PATH', CACHE_PATH . 'caches_model' . DIRECTORY_SEPARATOR . 'caches_data' . DIRECTORY_SEPARATOR);
// 定义在单独操作内容的时候，同时更新相关栏目页面
define('RELATION_HTML', true);

pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
pc_base::load_app_func('util');
pc_base::load_sys_class('format', '', 0);

/**
 * 商品管理
 */
class goods extends admin
{

    private $db,$type;

    public $siteid;

    public function __construct()
    {
        parent::__construct();
        $this->db = pc_base::load_model('goods_model');
        $this->type = pc_base::load_model('goods_type_model');
        $this->siteid = get_siteid();
    }

    /**
     * 商品列表
     */
    public function index ()
    {
        //获取管理员真实姓名数据
        $admin_model = pc_base::load_model('admin_model');
        $adminInfo = $admin_model->getRealnameInfo();
        
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $where = ' siteid = '.$this->siteid.' AND status <> 2 ';
        if(isset($_GET['type']) && !empty($_GET['type'])) {
            $type = strip_tags(trim($_GET['type']));
            $where .= " AND type = {$type}";
        }
        if(isset($_GET['title']) && !empty($_GET['title'])) {
            $title = strip_tags(trim($_GET['title']));
            $where .= " AND `cn_name` like '%$title%'";
        }
        $goods_list = $this->db->listinfo($where, 'id DESC', $page, 20);
        $pages = $this->db->pages;
        $select_categorys = $this->type->getTypes($_GET['type']);
        include $this->admin_tpl('goods_list');
    }

    /**
     * 添加商品
     */
    public function add ()
    {
        if(isset($_POST['dosubmit']) && ! empty($_POST['dosubmit'])) {
            $goods = $this->check($_POST['goods'],'add');
            $id = $this->db->insert($goods, true);
            if ($id) {

                //记录行为日志
                $log_content = '<span style="color:green;">添加商品</span>[商品id：'.$id.'，商品中文名称：'.$goods['cn_name'].']';
                $this->manage_admin_log($log_content);

                showmessage(L('operation_success'), '?m=goods&c=goods&a=index');
            } else {
                showmessage(L('operation_failure'), HTTP_REFERER);
            }
        } else {
            $show_validator = '';
            $select_categorys = $this->type->getTypes();
            include $this->admin_tpl('goods_add');
        }
    }

    /**
     * 商品修改
     */
    public function edit ()
    {
        if (! isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        if(isset($_POST['dosubmit']) && ! empty($_POST['dosubmit'])) {
            $goods = $this->check($_POST['goods']);
            $id = $this->db->update($goods, array('id' => $id));
            if ($id) {

                //记录行为日志
                $log_content = '<span style="color:blue;">修改商品</span>[商品id：'.$_GET['id'].'；商品中文名称：'.$goods['cn_name'].']';
                $this->manage_admin_log($log_content);

                showmessage(L('operation_success'), '?m=goods&c=goods&a=index');
            } else {
                showmessage(L('operation_failure'), HTTP_REFERER);
            }
        } else {
            $show_validator = '';
            $info = $this->db->get_one(array('id'=>$id));
            $select_categorys = $this->type->getTypes($info['type']);
            include $this->admin_tpl('goods_edit');
        }
    }

    /**
     * 商品删除
     */
    public function delete ()
    {
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if (intval($v)) {
                    $id[$k] = intval($v);
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode(',', $id);
        }
        $result = $this->db->update(array('status'=>2),"id in ('$id')");

        $cn_name = $_REQUEST['cn_name']?$_REQUEST['cn_name']:'删除多个商品或商品名称暂未获取到，请联系管理员！';
        //记录行为日志
        $log_content = '<span style="color:red;">删除商品</span>[商品id：'.$id.'；商品名称：'.$cn_name.']';
        $this->manage_admin_log($log_content);

        if ($result) {
            $goods_source_model = pc_base::load_model('goods_source_model');
            $goods_source_model->delete("goods_id in ('$id')");
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L('operation_failure'), HTTP_REFERER);
        }
    }

    /**
     * 表单验证
     * 
     * @param array $data
     *            表单传递的值
     * @param string $a
     *            add/edit添加操作时，自动加上默认值
     */
    private function check($data, $a = '')
    {
        if ($a == 'add') {
            $data['siteid'] = $this->siteid;
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['created_by'] = $_SESSION['userid'];
            $data['update_time'] = date('Y-m-d H:i:s');
            $data['updated_by'] = $_SESSION['userid'];
        } else {
            $data['update_time'] = date('Y-m-d H:i:s');
            $data['updated_by'] = $_SESSION['userid'];
        }
        return $data;
    }

    /**
     * 检验标题否存在，避免标题重复
     */
    public function public_check_goods ($title)
    {
        if(!$title) showmessage(L('no-title'), HTTP_REFERER);;
        if(pc_base::load_config('system', 'charset')=='gbk') {
            $title = safe_replace(iconv('UTF-8', 'GBK', $title));
        }
        $title = addslashes($title);
        if($_GET['id']) {
            $id = intval($_GET['id']);
            $r = $this->db->get_one(array('id'=>$id, 'siteid' => $this->siteid));
            if($r['title'] == $title) {
                return true;
            }
        }
        $r = $this->db->get_one(array('siteid' => $this->siteid, 'title' => $title), 'id');
        if($r['id']) {
            return false;
        } else {
            return true;
        }
    }
}